<?php

namespace app\admin\controller;

use app\common\controller\Admin;
use think\Request;
use app\common\model\Type as TypeModel;
use app\admin\model\AdminConfig;
use think\Session;

class Configure extends Admin {

    /**
     * 配置管理页
     * @return type
     */
    public function index() {
        $configGroup = TypeModel::where('pid', 3)->where('display', 1)->order('pid asc,list_order asc')->column('name', 'describe');
        $siteList = [];

        $index = 0;
        foreach ($configGroup as $key => $group) {
            $siteList[$key]['name'] = $key;
            $siteList[$key]['title'] = $group;
            $siteList[$key]['list'] = [];
            $siteList[$key]['active'] = !$index ? true : false;
            $index++;
        }
        $list = AdminConfig::all();
        foreach ($list as $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], TRUE);
            $siteList[$v['group']]['list'][] = $value;
        }

        $this->assign('configGroup', $configGroup); //
        $this->assign('siteList', $siteList);
        return $this->fetch();
    }

    /**
     * 更新配置
     * @param Request $request
     */
    public function edit(Request $request) {
        $data = $request->param();

        $group = $data['group'];

        $row = $data['row'];

        foreach ($row as $name => $value) {
            AdminConfig::where('group', $group)->where('name', $name)->update(['value' => $value]);
        }
        Session::set('adminConfigure', getAdminConfigure());
        return $this->success();
    }

    /**
     * 添加或编辑分类
     * @param Request $request
     * @return type
     */
    public function editType(Request $request) {
        $data = $request->param();

        if ($data['id']) {
            TypeModel::where('id', $data['id'])->update($data);
        } else {
            TypeModel::insert($data);
        }

        $list = TypeModel::order('pid asc,list_order asc')->select();
        $this->success('sss', '', $list);
    }

    /**
     * 删除菜单
     * @return type
     */
    public function delType() {
        $data = $this->request->param();
        TypeModel::where('id', $data['id'])->delete();
        $list = TypeModel::order('pid asc,list_order asc')->select();
        return $this->success('success', '', $list);
    }

    /**
     * 更新排序
     * @param Request $request
     * @return type
     */
    public function setSort(Request $request) {
        $data = $request->param();

        foreach ($data as $key => $typeid) {
            TypeModel::where('id', $typeid)->update(['list_order' => $key]);
        }

        return $this->success('success', '', $data);
    }

}
